<template>
  <a-input v-model:value="code" @change="handleChange" :readonly="switchValue">
    <template #addonAfter>
      <div>
        <!--        <a-button shape="circle" type="text" style="margin-right: 3px" @click="handleCopy"> Copy </a-button>-->
        <a-switch v-model:checked="switchValue" v-bind="props" :disabled="!attrs.formDisabled" @change="handleSwitchChange" />
      </div>
    </template>
  </a-input>
</template>
<script setup>
  import { useAttrs, ref, unref, computed } from 'vue';
  import { executeRuleByCode } from '@/api/common/api';
  // import { useRuleFormItem } from '@/hooks/component/useFormItem';
  import { useCopyToClipboard } from '@/hooks/web/useCopyToClipboard';
  import { useMessage } from '@/hooks/web/useMessage';
  // switch切换框的props
  const props = defineProps({
    checkedChildren: String,
    unCheckedChildren: String,
    size: String,
  });
  // 获取组件的attrs
  const attrs = useAttrs();
  // console.log('==============> ', attrs, props);

  const code = ref('');
  const emit = defineEmits(['change', 'update:value']);
  const handleChange = async (e) => {
    let text = e?.target?.value ?? '';
    if (text && !!props.trim) {
      text = text.trim();
    }
    code.value = text;
    emit('change', text);
    emit('update:value', text);
  };
  const switchValue = ref(false);
  const handleSwitchChange = async (e) => {
    if (e) {
      const res = await executeRuleByCode(attrs.orderType);
      code.value = res;
      switchValue.value = e;
      emit('change', res);
    }
  };
  if (attrs?.isAutoGenerate) {
    if (attrs?.formDisabled) {
      handleSwitchChange(true);
    } else {
      switchValue.value = attrs?.isAutoGenerate;
    }
  }
  //   复制单号
  const { createMessage } = useMessage();
  const { clipboardRef, copiedRef } = useCopyToClipboard();

  const handleCopy = async () => {
    const value = code.value;
    if (!value) {
      createMessage.warning('请输入要拷贝的内容！');
      return;
    }
    clipboardRef.value = value;
    if (unref(copiedRef)) {
      createMessage.success('已复制');
    }
  };
</script>
<style scoped lang="less"></style>
